<template>
  <div class="container">
    <div class="app-container">
      <el-tree default-expand-all :data="depts" :props="defaultProps" draggable>
        <template #default="{data}">
          <el-row type="flex">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <div>
                <!-- 管理员 -->
                <span class="text-manager">{{ data.managerName }}</span>
                <!-- 操作栏 -->
                <sa :node="data" @add="addDalo" @edit="editDept" @del="delDept" />
              </div>
            </el-col>
          </el-row>
        </template>
      </el-tree>
      <dalog-vue ref="deptRef" :show-dialog.sync="flag" :pid.sync="pid" @close="flag= false" @update-list="louserList" />
    </div>
  </div>
</template>
<script>
import { deleteDepartmentById, getDepartments } from '@/api/user'
import sa from './components/sa.vue'

import { listTree } from '@/utils'
import dalogVue from './components/dalog.vue'

export default {
  name: 'Department',
  components: { sa, dalogVue },
  data() {
    return {
      depts: [

      ],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      flag: false,
      pid: 0
    }
  },
  mounted() {
    this.louserList()
  },
  methods: {
    async louserList() {
      const res = await getDepartments()
      // 对数据进行分部门处理
      const a = listTree(res, 0)
      this.depts = a
    },
    // 加载添加框
    addDalo(id) {
      this.flag = true
      this.pid = id
    },
    // 加载修改框
    async editDept(pid) {
      this.pid = pid
      // 以保证数据已经请求回来了，再展示弹框（解决短暂留白的情况）
      await this.$refs.deptRef.getDetail(pid)
      this.flag = true
    },
    // 删除列表操作
    async delDept(id) {
      const res = window.confirm('您确认要删除该部门吗？')
      if (res) {
        await deleteDepartmentById(id)

        this.$message.success('删除部门成功')
        this.louserList()
      }
    }
  }
}

</script>
<style lang="scss" scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
  .el-row {
    width: 100%;
  }

  .text-manager {
    margin-right: 20px;
  }
}
</style>
